package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.GoodsDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.TerGoods;
import com.framework.entity.ter.TerGoodsBanner;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.service.*;
import com.framework.utils.string.StringUtil;
import com.framework.validator.Assert;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, TerGoods> implements GoodsService {

	@Autowired
	private AgentService agentService;
	@Autowired
	private GoodsBannerService goodsBannerService;
	@Autowired
	private TranOrderService tranOrderService;
	@Autowired
	private TerminalInfoService terminalInfoService;
	@Autowired
	private GoodsService goodsService;

	@Override
	public List<TerGoods> queryGoodsList(String token, String name,Integer goodsType) {
		if(StringUtils.isBlank(token)){
			throw new RRException(RespCode.NOT_PARAM_ERROR);
		}
		//查询代理商数据缓存
		SysAgent agent = agentService.queryAgentByToken(token);
		return baseMapper.queryGoodsList(agent.getDeptId(),name,1,goodsType);
	}

	@Override
	public TerGoods queryGoodsById(Long goodsId) {
		if(goodsId == null || goodsId == 0){
			throw new RRException(RespCode.NOT_PARAM_ERROR);
		}
		TerGoods t = new TerGoods();
		t.setGoodsId(goodsId);
		t.setIsShow(1);
		return baseMapper.selectOne(t);
	}

	@Override
	public Map<String, Object> queryGoodsInfo(String token, Long goodsId) {
		Map<String,Object> map = new HashMap<>(2);
		if(goodsId == null || goodsId == 0 || StringUtils.isBlank(token)){
			throw new RRException(RespCode.NOT_PARAM_ERROR);
		}
		//查询代理商数据缓存
		SysAgent agent = agentService.queryAgentByToken(token);
		Long deptId = agent.getDeptId();
		TerGoods goods = queryGoodsById(goodsId);
		Assert.isNull(goods,"未查询到商品信息");
		if(deptId.intValue() != goods.getDeptId().intValue()){
			throw new RRException("9000","商品渠道不一致");
		}
		List<TerGoodsBanner> list = goodsBannerService.queryGoodsBannerList(goodsId);
		map.put("goods",goods);
		map.put("bannerList",list);
		return map;
	}

	@Override
	public PageUtils queryGoodsInfoList(Map<String, Object> params) {
		Integer pageSize=Integer.valueOf(params.get("limit").toString());
		Integer currPage=Integer.valueOf(params.get("page").toString());
		params.put("start",(currPage-1)*pageSize);
		params.put("limit",pageSize);
		List<Map<String,Object>> list=baseMapper.queryGoodsInfoList(params);
        List<TerGoodsBanner> bannersList = goodsBannerService.selectList(null);

        for (Map<String, Object> temp :list) {
            Long goodsId = Long.valueOf(temp.get("goodsId").toString());
            List<TerGoodsBanner> collect = bannersList.stream().filter(e -> e.getGoodsId().equals(goodsId)).collect(Collectors.toList());
            temp.put("bannersList",collect);
			temp.put("bannersCount",collect.size());
		}
		Integer count=baseMapper.queryGoodsInfoCount(params);
		return new PageUtils(list,count,pageSize,currPage);
	}

	@Override
	public Integer addnNewGoods(String infoUrl, String coverUrl, HttpServletRequest request, Long depId)  {
		TerGoods terGoods=new TerGoods();
		terGoods.setIsShow(1);
		terGoods.setCreateTime(new Date());
		terGoods.setGoodsType(Integer.valueOf(request.getParameter("goodsType")));
		terGoods.setDeptId(depId);
		terGoods.setLeastNum(Integer.valueOf(request.getParameter("leastNum")));
		terGoods.setModel(request.getParameter("model"));
		terGoods.setName(request.getParameter("name"));
		terGoods.setPrice(new BigDecimal(request.getParameter("price")));
		terGoods.setTerminalType(Integer.valueOf(request.getParameter("terminalType")));
		terGoods.setSort(baseMapper.queryMaxSort(depId)+1);
		terGoods.setInfoImg(infoUrl);
		terGoods.setCoverImg(coverUrl);
		Integer count = baseMapper.insert(terGoods);
		return count;
	}

	@Override
	public TerGoods queryGoodsByGoodsId(Long goodsId) {
		if(goodsId == null || goodsId == 0){
			throw new RRException(RespCode.NOT_PARAM_ERROR);
		}
		TerGoods t = new TerGoods();
		t.setGoodsId(goodsId);
		return baseMapper.selectOne(t);
	}

	@Override
	public Integer updateGoods(String coverUrl, String infoUrl, HttpServletRequest request) {
		TerGoods terGoods=new TerGoods();
		terGoods.setGoodsId(Long.valueOf(request.getParameter("goodsId")));
		terGoods.setIsShow(Integer.valueOf(request.getParameter("isShow")));
		terGoods.setGoodsType(Integer.valueOf(request.getParameter("goodsType")));
		terGoods.setLeastNum(Integer.valueOf(request.getParameter("leastNum")));
		terGoods.setModel(request.getParameter("model"));
		terGoods.setName(request.getParameter("name"));
		terGoods.setPrice(new BigDecimal(request.getParameter("price")));
		terGoods.setTerminalType(Integer.valueOf(request.getParameter("terminalType")));
		terGoods.setSort(Integer.valueOf(request.getParameter("sort")));
		if(!StringUtil.isEmpty(coverUrl)){
			terGoods.setCoverImg(coverUrl);
		}
		if (!StringUtil.isEmpty(infoUrl)){

			terGoods.setInfoImg(infoUrl);
		}
		Integer count = baseMapper.updateById(terGoods);
		return count;
	}

	@Override
	public Map<String, Object> queryGoodsPresentInfo(String token, Long goodsId) {
		SysAgent agent = agentService.queryAgentByToken(token);
		//SysAgent agent=agentService.queryAgentById(889848L); 测试用
		List<Map<String,Object>> tranOrders=tranOrderService.queryOrderListByAgentIdAndGoodsId(agent.getAgentId(),goodsId);
		if(tranOrders==null || tranOrders.size()==0){
			throw new RRException("9000","您并未成功购买此商品");
		}
		TerGoods goods = goodsService.queryGoodsById(goodsId);
		;
		Map<String, Object> paramsMap=new HashMap<>();//查询map
		Map<String,Object> result=new HashMap<>();//结果
		List<TerTerminalInfo> terLists=new ArrayList<>();
		paramsMap.put("terminalType",goods.getTerminalType());
		paramsMap.put("deptId",agent.getDeptId());
		for (Map<String, Object> stringObjectMap :tranOrders) {
			Map<String, Object> map=tranOrderService.queryNoticeDetail(Long.valueOf(stringObjectMap.get("orderId").toString()));
			List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
			for (Map<String, Object> objectMap :list) {
				Object startNo = objectMap.get("startSn");
				Object endNo = objectMap.get("endSn");
				paramsMap.put("startNo",startNo);
				paramsMap.put("endNo",endNo);
				terLists.addAll(terminalInfoService.queryTerListByNo(paramsMap));
			}
		}
		result.put("list",terLists);
		return result;
	}

	@Override
	public void sellGood(Long goodsId) {
		TerGoods g = baseMapper.selectById(goodsId);
		if(g==null){
			throw  new RRException("9000","未查询到此商品");
		}
		g.setIsShow(1);
		baseMapper.updateAllColumnById(g);
	}

	@Override
	public PageUtils queryUnSoldList(Map<String, Object> params) {
		params.put("isShow","2");
		return queryGoodsInfoList(params);
	}

	@Override
	public void unSellGood(Long goodsId) {
		TerGoods g = baseMapper.selectById(goodsId);
		if(g==null){
			throw  new RRException("9000","未查询到此商品");
		}
		g.setIsShow(2);
		baseMapper.updateAllColumnById(g);
	}

	@Override
	public List<TerGoods> queryGoodsListForH5(String token) {
		SysAgent sysAgent = agentService.queryAgentByToken(token);
		return selectList(new EntityWrapper<TerGoods>().eq("dept_id",sysAgent.getDeptId()).eq("integral_flag",1));
	}

	@Override
	public Map<String, Object> queryGoodsInfoForH5(String token, Long goodsId) {
		Map<String,Object> map = new HashMap<>(2);
		if(goodsId == null || goodsId == 0 || StringUtils.isBlank(token)){
			throw new RRException(RespCode.NOT_PARAM_ERROR);
		}
		//查询代理商数据缓存
		SysAgent agent = agentService.queryAgentByToken(token);
		Long deptId = agent.getDeptId();
		TerGoods goods = selectById(goodsId);
		Assert.isNull(goods,"未查询到商品信息");
		if(deptId.intValue() != goods.getDeptId().intValue()){
			throw new RRException("9000","商品渠道不一致");
		}
		List<TerGoodsBanner> list = goodsBannerService.queryGoodsBannerList(goodsId);
		map.put("goods",goods);
		map.put("bannerList",list);
		return map;
	}
}
